package com.itheima;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Set;

@WebServlet("/ServletUpdata")
public class ServletUpdata extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String stuid = request.getParameter("name");
        String realPath = getServletContext().getRealPath("stu.txt");
        HashMap<String, Student> hm = (HashMap<String, Student>) request.getSession().getAttribute("stulist");
        Set<String> setlist = hm.keySet();
        //如果是通过查询访问过来的请求,就跳转修改页面
        if (stuid!=null){
            for (String set : setlist) {
                request.getSession().setAttribute("id",hm.get(set).getId());
                request.getSession().setAttribute("name",hm.get(set).getName());
                request.getSession().setAttribute("sex",hm.get(set).getSex());
                request.getSession().setAttribute("score",hm.get(set).getScore());
            }
            request.getRequestDispatcher("updata.jsp").forward(request,response);
            //如果是修改页面访问过来的请求,就执行逻辑修改
        }else{
            String id = request.getParameter("stuid");
            String name = request.getParameter("stuname");
            String sex = request.getParameter("stusex");
            String score = request.getParameter("stuscore");
            BufferedReader br = new BufferedReader(new FileReader(realPath));
            String s;
            while ((s=br.readLine())!=null){
                String[] split = s.split(":");
                if (split[0].equals(id)){
                    //这里获取老数据的学号存入集合,导致学号不能修改
                    hm.put(split[0],new Student(id,name,sex,Integer.parseInt(score)));
                }
            }
            br.close();
            BufferedWriter bwx = new BufferedWriter(new FileWriter(realPath));
            bwx.write("");
            BufferedWriter bw = new BufferedWriter(new FileWriter(realPath,true));
            Set<String> setlist2 = hm.keySet();
            for (String s1 : setlist2) {
                bw.write(hm.get(s1).getId()+":"+hm.get(s1).getName()+":"+hm.get(s1).getSex()+":"+hm.get(s1).getScore());
                bw.newLine();
                bw.flush();
            }
            bw.close();
            response.sendRedirect(request.getContextPath()+"/ServletFind");
        }


    }
}
